<?php
/**
 * PHP Snippet for http authentication. 
 * 
 * Include this file into any areas that should be secured.
 * @author James Ravenscroft
 * @license LGPL
 * @package Edify
 */


ob_start();
include("../config.php");
include("../lib/dbal/dbal.php");
include("../lib/smarty/Smarty.class.php");
$prefix = $database_prefix;

//Start database connection
$dbh = new dbal("$database_protocol://$database_username:$database_password@$database_host/$database_database");
$dbh->setCacheDir("../cache"); 


if (isset($_GET['Authorization'])) {
    // Check for the HTTP authentication string in $_GET['Authorization'], 
    // and put it in the $auth variable
    if (preg_match('/Basic\s+(.*)$/i', $_GET['Authorization'], $auth)) {
        // Split the string, base64 decode it, and place the values into 
        // the $authName and $authPassword variables
        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode($auth[1]));
        // Check the values of $authName and $authPass using your login routine
    }
}
if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) && empty($_COOKIE['session_id']))
{
	print "started logging in...<br>".
	//login process
	$password = crypt($_SERVER['PHP_AUTH_PW'], substr($_SERVER['PHP_AUTH_PW'],0,2));
	$dbh->compile("SELECT * FROM {$prefix}_users WHERE username= :username AND password= :password".
	" AND admin=1 LIMIT 1");
	$r = $dbh->query(array('username' => $_SERVER['PHP_AUTH_USER'],
	'password' => $password));
	
	if($r->_length > 0)
	{
		$admin = $r->getNext();
		$sid = crypt(rand());
		setcookie("session_id", $sid);
		$dbh->compile("INSERT INTO {$prefix}_sessions(user_id,time,cookie, admin)".
		" VALUES(:id, NOW(), :sid, 1)");
		$dbh->execute(array('id' => $admin['user_id'],'sid' => $sid));

		header("Location: {$_SERVER['PHP_SELF']}?{$_SERVER['QUERY_STRING']}");
		exit;
	}
}

if(isset($_COOKIE['session_id']))
{
	//delete old sessions (20 mins old or more)
	$dbh->execute("DELETE FROM {$prefix}_sessions WHERE time<(NOW()-600)");
	$sid = mysql_escape_string($_COOKIE['session_id']);
	$dbh->compile("SELECT * FROM {$prefix}_users u, {$prefix}_sessions s WHERE "
	."s.cookie = :sid"
	." AND s.user_id=u.user_id AND s.admin=1");
	$r = $dbh->query(array('sid' => $_COOKIE['session_id']));
	
	$data = $r->getNext();
	
	if(!empty($data))
	{
		$dbh->compile("UPDATE {$prefix}_sessions SET time = NOW() WHERE cookie = :sid");
		$dbh->execute(array('sid' => $_COOKIE['session_id']));
		define(SESSION_AUTHENTICATED, true);
	}
	else
	{
		setcookie('session_id', null);
		dropout();
	}
}
else
{
	dropout();
}

function dropout()
{
	global $error_text, $zone_title;
	header('WWW-Authenticate: Basic realm="'.$zone_title.'"');
    header('HTTP/1.0 401 Unauthorized');
    echo $error_text;
    mysql_close();
    exit();
}

?>